// src/mock/api.ts
export type PostType = 'secondhand' | 'parttime'
export interface Post {
  id: String
  crtim: String
  type: PostType
  title: String
  content: String
  cover?: String
  price?: number     // 二手价格
  wage?: String      // 兼职薪资
  location?: String
  createdAt: number  // ts
}

export interface Comment {
  id: string
  postId: string
  author: string
  content: string
  createdAt: number
}


export async function mockPostSearch(params: {
  keyword?: string
  type?: PostType | 'all'
  page?: number
  pageSize?: number
}) {
  // 这里模拟 /post/search（关键词 + 类型），不实际请求后端
  const { keyword = '', type = 'all', page = 1, pageSize = 10 } = params || {}
  const token = localStorage.getItem('token')

  const response = await fetch('http://www.crazyzzcc.online:32004/campus/post', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

  const data1 = await response.json()

  let data = data1.data.items

  if (type !== 'all') data = data.filter(p => p.type === type)
  if (keyword.trim()) {
    const k = keyword.trim().toLowerCase()
    data = data.filter(p => (p.title + p.content).toLowerCase().includes(k))
  }

  const start = (page - 1) * pageSize
  const end = start + pageSize
  const pageList = data.slice(start, end)
  return {
    list: pageList,
    total: data.length,
    hasMore: end < data.length
  }
}

export async function mockGetPostById(id: string) {
  const token = localStorage.getItem('token')
  const response = await fetch(`http://www.crazyzzcc.online:32004/campus/post/one/${id}`, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    },
  })
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`)
  }
  const data_a = await response.json()
  let data = data_a.data
  return data || null
}
